package com.cndw.kungfu.event.model;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.event.BaseHandler;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.ext.XmlProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.activity.domain.IntervalBroadcast;
import com.cndw.kungfu.model.sys.ChatMain;

public class IntervalBroadCastHandle extends BaseHandler implements Runnable {
	private static final List<IntervalBroadcast> broadcastList = XmlProcesser.processXml(IntervalBroadcast.class, ConstantsConfig.getLocaleResource()
			+ "timeBroadcast.xml");

	private static int currentIndexId = -1;

	static {

		Collections.sort(broadcastList);
	}

	private IntervalBroadCastHandle() {

	}

	@Override
	public void run() {
		IntervalBroadcast currentBroadcast = broadcastList.get(currentIndexId);
		broadcast(currentBroadcast);
		start();
	}

	private void broadcast(IntervalBroadcast currentBroadcast) {
		if (currentBroadcast != null && currentBroadcast.getContent() != null) {
			ChatMain.systemMessage(currentBroadcast.getContent());
		}
	}

	public static void runBoss() {
		IntervalBroadCastHandle currentTask = new IntervalBroadCastHandle();
		currentTask.start();
	}

	/**
	 * 启动广播队列,一次保证只1个任务
	 */
	private void start() {
		int morningTime = TimeProcesser.getMorningTime();
		int currentSconds = TimeProcesser.getUnixTime() - morningTime;

		int tryTimes = -1;
		int tempIndexId = currentIndexId;

		int currentWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
		while (tryTimes <= broadcastList.size()) {
			tryTimes++;

			tempIndexId++;
			if (tempIndexId == broadcastList.size()) {
				tempIndexId = 0;
				currentIndexId = 0;
			}
			IntervalBroadcast currentBroadcast = broadcastList.get(tempIndexId);
			if (currentBroadcast.getSpecialWeek() > 0) {// 限制了特别的某天
				if ((currentBroadcast.getSpecialWeek() & (1 << currentWeek)) <= 0) {
					continue;
				}
			}

			if (currentBroadcast.getDate() != null) {
				try {
					int specialData = TimeProcesser.getUnixTimeByString(currentBroadcast.getDate(), "yyyy-MM-dd");
					if (specialData != TimeProcesser.getMorningTime()) {
						continue;
					}
				} catch (ParseException e) {
					e.printStackTrace();
					continue;
				}

			}

			int delay = currentBroadcast.getInitTime() - currentSconds;
			// 编号比上次编号靠后的还未执行的广播.立即执行
			if (delay >= -20 && delay <= 0 && tempIndexId > currentIndexId) {
				broadcast(currentBroadcast);
				continue;
			}

			if (currentIndexId >= 0 && tempIndexId == 0 && delay < 0) {
				delay += 86400;
			}

			if (delay > 0) {
				currentIndexId = tempIndexId;// 下次执行这编号

				Context.getTimerServer().scheduleSeconds(this, delay);

				break;
			}
		}
	}
}
